import React, {useState} from 'react';
import ReactEcharts from 'echarts-for-react';
import {Spin} from 'antd';
import moment from 'moment';
import {colorPalette} from './helper.js';
import {cloneDeep} from 'lodash';

const defaultAxisLabel = {
    show: true,
};

export default props => {
    const {
        loading,
        chartData,
        yAxisLabel = defaultAxisLabel,
        style = {height: '380px', width: '100%'},
        handleClick = () => {},
        dataZoom = false,
        gridBottom = 60,
    } = props;

    const {legend, xAxis, yAxis = [], series} = chartData.chart ?? {};

    const yAxisData = cloneDeep(yAxis);

    if (yAxisData?.length <= 0) {
        yAxisData[0] = {
            type: 'value',
            name: '',
            axisLabel: yAxisLabel
        };
    }


    const option = {
        color: colorPalette,
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                },
            },
            formatter(params) {
                const date = params[0].axisValue;
                let result = `${date}<br/>`;
                result += params
                    ?.map(entry => `${entry.marker} ${entry.seriesName} ${entry.data.value}`)
                    .join('<br >');
                return result;
            }
        },
        legend: {
            ...legend,
            top: 17,
            left: 20,
        },
        dataZoom: dataZoom && [
            {
                type: 'slider',
                show: true,
                xAxisIndex: [0],
                start: 1,
                end: 100,
            },
            {
                type: 'inside',
                show: true,
                xAxisIndex: [0],
                start: 1,
                end: 100
            },
        ],
        grid: {
            containLabel: false,
            bottom: gridBottom,
        },
        xAxis,
        yAxis: yAxisData,
        series
    };

    if (option) {
        return (
            <Spin spinning={loading}>
                <ReactEcharts
                    option={option}
                    style={style}
                    onEvents={{
                        click: handleClick
                    }}
                />
            </Spin>
        );
    }
    return <Spin spinning />;
};
